package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.util.Map;

public class JWTUtil {
    private static final String secretKey = "天王盖地虎,宝塔镇河妖哈哈哈哈哈";

    public static String createJWT(Map map) throws JOSEException {
        //设置头部信息,头部+负载信息+签名信息
        JWSHeader jwsHeader = new JWSHeader
                .Builder(JWSAlgorithm.HS256)//设置加密方式
                .type(JOSEObjectType.JWT).build();//设置jwt常量
        System.out.println(jwsHeader);
        //2.载荷(存放用户信息,不要放敏感信息)
        Payload payload = new Payload(map);
        //3.签名(头部+载荷+密钥)
        JWSObject jwsObject = new JWSObject(jwsHeader, payload);
        MACSigner macSigner = new MACSigner(secretKey);//MACSigner对称加密方式
        jwsObject.sign(macSigner);//数字签名(加密)
        return jwsObject.serialize();
    }

    public static Boolean decode(String jwt) throws Exception {
        //通过jwt字符串反序列化获取jwsObject对象
        JWSObject jwsObject = JWSObject.parse(jwt);
        MACVerifier macVerifier = new MACVerifier(secretKey);
        return jwsObject.verify(macVerifier);
    }

    //获取jwt中用户信息(载荷)
    public static Map<String, Object> getUserMap(String jwt) throws Exception {
        JWSObject jwsObject = JWSObject.parse(jwt);
        return jwsObject.getPayload().toJSONObject();
    }
}
